/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package papacharly.encheres.ui;

import papacharly.encheres.client.ClientWrapper;
import papacharly.encheres.idl.ServeurPackage.User;
import papacharly.encheres.log.Logger;

/**
 *
 * @author user01
 */
public class GestionEnchereHandler {

    private Logger log = Logger.getLogger(this.getClass().getSimpleName());
    private ClientWrapper clientWrapper = new ClientWrapper();
    private GestionEncheres ui = null;
    private User user = null;

    public GestionEnchereHandler(final GestionEncheres ui) {
        this.ui = ui;
    }

    public String createUser() {
        log.debug("createUser");
        String mdp = "";

        // Prepare pay load user
        User currentUser = new User();
        currentUser.idUser = -1;
        currentUser.pseudo = ui.getTxtUser().getText();
        currentUser.nom = ui.getTxtNomUser().getText();
        currentUser.prenom = ui.getTxtPrenomUser().getText();
        currentUser.adresse = ui.getTxtAdresseUser().getText();
        currentUser.email = ui.getTxtMailUser().getText();
        currentUser.telephone = ui.getTxtPhoneUser().getText();
        currentUser.password = "default";

        // Call corba server
        mdp = clientWrapper.getServeurCorba().createUser(currentUser);

        // TODO - Update the client (get a correct Id)

        if (mdp.equals("")) {
            log.debug("createUser - user not created");
        } else {
            // Update User
            currentUser.password = mdp;
            user = currentUser;

            // Update UI
            ui.getBtnCreateUser().setEnabled(Boolean.FALSE);
            ui.setLoginState(Boolean.TRUE);
            ui.displayMdp(mdp);
        }

        return mdp;
    }

    public boolean login(){
        log.debug("logout");

        boolean login = false;

        // Call corba server
        login = clientWrapper.getServeurCorba().login(ui.getTxtLogin().getText(), ui.getLslPassword().getText());

        // TODO - Update the client (get a correct Id)

        if (!login) {
            log.debug("logout - user not login");
            ui.displayLoginKo();
        } else {
            ui.setLoginState(Boolean.TRUE);
        }

        return login;
    }

    public boolean logout(){
        log.debug("logout");

        boolean logout = false;

        // Call corba server
        // TODO - Use the pseudo field of the user
        logout = clientWrapper.getServeurCorba().logout("pseudo");

        if (!logout) {
            log.warn("logout - user not logout");
            ui.displayLogoutKo();
        } else {
            ui.setLoginState(Boolean.FALSE);
        }

        return logout;
    }

    public User getUser() {
        return user;
    }
}
